const express = require('express');
const router = express.Router();

// 导入 shortid
const shortid = require("shortid");

const AccountModel = require("../../models/AccountModel");

// 导入 moment
const moment = require("moment");

// 导入中间件
let checkLoginMiddleware = express.static("./middleware/checkLoginMiddleware")

router.get('/', checkLoginMiddleware, function(req, res, next) {
  res.redirect("/account");
});

/* 记账本列表 */
router.get('/account', checkLoginMiddleware,  async function(req, res, next) {
  if (!req.session.username) {
    return  res.redirect("/login");
  }

  try {
    const accounts = await AccountModel.find().sort({time: -1}).exec();
    console.log(accounts)
    // 格式化时间
    res.render("list", {accounts,moment});
  } catch (e) {
    res.render("fail",{msg: "获取失败", url: "/account"})
  }
});

// 添加记录
router.get("/account/create",checkLoginMiddleware, (req,res, next) => {
  res.render("create")
})

// 新增记录
router.post("/account",checkLoginMiddleware, (req, res,next) => {
  // 生成id
  let id = shortid.generate();
  req.body.type = Number(req.body.type);
  // 转换时间对象
  req.body.time = moment(req.body.time).toDate();
  // 将类型转换为Number

  // 获取请求体的数据
  console.log(req.body);
  // 写入文件
  // db.get("accounts").unshift({id, ...req.body}).write();
  AccountModel.create({id, ...req.body}).then(data => {
    // 成功提醒
    res.render("success",{msg: "添加成功", url: "/account"})
  }).catch(err => {
    res.render("fail",{msg: "添加失败", url: "/account/create"})
  })
})


// 删除记录
router.get("/account/:id", checkLoginMiddleware,(req, res) => {
  let id = req.params.id;
  AccountModel.deleteOne({_id: id}).then(data => {
    // 成功提醒
    res.render("success",{msg: "删除成功", url: "/account"})
  }).catch(err => {
    res.render("fail",{msg: "删除失败", url: "/account"})
  })
})

// 添加首页的路由规则


module.exports = router;
